#include "GPUBuffer.h"
#include "Logger.h"
#include "Exception.h"

NS_B2D_BEGIN

GPUBuffer::lock_guard::lock_guard(GPUBuffer& buffer, LockMode mode, void** dst, size_t offset, size_t size)
	: mBuffer(buffer)
{
	mBuffer.lock(mode, dst, offset, size);
}

GPUBuffer::lock_guard::~lock_guard(void)
{
	mBuffer.unlock();
}

GPUBuffer::GPUBuffer(void)
	: mBufferSize(0)
	, mBufferUsage(BufferUsage::STATIC_DRAW)
	, mIsLocked(false)
{

}

GPUBuffer::~GPUBuffer(void)
{

}

void GPUBuffer::lock(LockMode mode, void** dst, size_t offset, size_t size)
{
	// Unlock first...
	if( mIsLocked == true )
		unlock();

	// Check for overflow
	size_t lastByte = offset + size;
	if( lastByte > mBufferSize )
	{
		B2D_THROW(Exception::BUFFER_OVERFLOW_EXCEPTION,
			"Unable to lock buffer as the memory range requested overflow the memory allocated");
	}

	lockImpl(mode, dst, offset, size);
	mIsLocked = true;
}

void GPUBuffer::unlock(void)
{
	if( mIsLocked == true )
	{
		unlockImpl();
		mIsLocked = true;
	}
}

NS_B2D_END